package com.example.services;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_01;
    private EditText et_02;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_01).setOnClickListener(this);
        findViewById(R.id.btn_02).setOnClickListener(this);
        et_01 = findViewById(R.id.et_01);
        et_02 = findViewById(R.id.et_02);
    }


    @Override
    public void onClick(View view) {
        boolean mIsBound = false;
        String result;
        Intent intent = new Intent(this, MyService.class);
        switch (view.getId()) {
            case R.id.btn_01:
                //绑定并连接远端service
                bindService(intent, conn, BIND_AUTO_CREATE);
                break;
            case R.id.btn_02:
                //解绑释放service
                unbindService(conn);
                break;
            default:
                break;
        }
    }

    //  创建ServiceConnection对象, 调用远程AIDL
    public final ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            double num1 = Double.parseDouble(et_01.getText().toString());
            double num2 = Double.parseDouble(et_02.getText().toString());
            //获取AIDL接口
            IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
            //调用AIDL提供的接口函数
            try {
                double res1 = iMyAidlInterface.multiplyNum(num1,num2);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                double res2 = iMyAidlInterface.plusNum(num1,num2);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                double res3 = iMyAidlInterface.subNum(num1,num2);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

}